<script lang="ts" setup>
import type { Ref } from 'vue'
import type { ComponentOptions } from '../../componentPanel/index'
import type { RuleOptionType } from './index'
import { inject, ref } from 'vue'
import { ruleTypeOptions } from './index'

const cmptSize = ref<any>('small')

const selectComponent = inject('selectComponent') as Ref<ComponentOptions>

function addRule() {
  selectComponent.value.rules?.push({
    label: '',
    value: '',
    message: '',
  })
}
function handleDeleteRule(row: RuleOptionType, index: number) {
  selectComponent.value.rules?.splice(index, 1)
}
function handleChangeRule(row: RuleOptionType) {
  const rule = ruleTypeOptions.find(item => item.label === row.label)
  if (rule) {
    row.label = rule.label
    row.required = rule.required || false
    row.value = rule.value
    row.message = rule.message
    row.validateCondition = rule.validateCondition
  }
}
</script>

<template>
  <ElTable :data="selectComponent.rules" :size="cmptSize" border>
    <ElTableColumn label="规则" width="100">
      <template #default="{ row }">
        <ElSelect v-model="row.label" placeholder="请选择规则" size="small" @change="handleChangeRule(row)">
          <ElOption v-for="item in ruleTypeOptions" :key="item.value" :label="item.label" :value="item.value" size="small" />
        </ElSelect>
      </template>
    </ElTableColumn>
    <ElTableColumn label="错误提示">
      <template #default="{ row }">
        <ElInput v-model="row.message" placeholder="请输入错误提示" size="small" />
      </template>
    </ElTableColumn>
    <ElTableColumn label="操作" width="60">
      <template #default="{ row, index }">
        <ElButton type="danger" :size="cmptSize" @click="handleDeleteRule(row, index)">
          <ElIcon class="delete-icon cursor-pointer">
            <Delete />
          </ElIcon>
        </ElButton>
      </template>
    </ElTableColumn>
  </ElTable>
  <div class="flex justify-end w-full">
    <ElButton type="primary" plain :size="cmptSize" style="margin-top: 10px;width: 100%;" @click="addRule">
      添加规则
    </ElButton>
  </div>
</template>
